// pages/terminal/chart/index.js
var app = getApp(), fetchApi = require("../../../../utils/httpPost.js")
const wxCharts = require("../../../../utils/wxcharts.js"), 
commonJs = require("../../../../component/common.js")
import Toast from '../../../../component/vant/toast/toast';
import * as echarts from '../../../../component/ec-canvas/echarts';


function getTempOption(option) {
  if(option!=undefined){
    return option;
  }
  return {
    legend: {
      data: ['暂无数据',],
      // data: [],
      top: 10,
      left: 'center',
      backgroundColor: 'red',
      z: 100
    },
    grid: {
      containLabel: true
    },
    tooltip: {
      show: true,
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['08:00', '09:00', '10:00', '11:00', '12:00'],
      // data: [],
      // show: false
    },
    yAxis: {
      x: 'center',
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      },
      min: 0, //设置y轴最小值
      max: 100, //设置y轴最大值
      interval: 20, //设置y轴刻度间隔
      // show: false
    },
    series: [
      {
      name: '暂无数据',
      type: 'line',
      smooth: true,
      data: [0, 0, 0, 0, 0,]
    }, 
    // {
    //   name: 'B',
    //   type: 'line',
    //   smooth: true,
    //   data: [12, 50, 51, 35, 70, 30, 20]
    // }, 
    // {
    //   name: 'C',
    //   type: 'line',
    //   smooth: true,
    //   data: [10, 30, 31, 50, 40, 20, 10]
    // }
  ]
  };
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    ecTemp: {
      onInit: function (canvas, width, height, dpr) {
        const barChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(barChart);
        barChart.setOption(getTempOption());
        return barChart;
      }
    },
    ecEle: {
      onInit: function (canvas, width, height, dpr) {
        const barChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(barChart);
        barChart.setOption(getTempOption());
        return barChart;
      }
    },
    ecList:[],
    isLoading:true,
    deviceNum:'',
    deviceId:0,
    categories:[],
    wenduData:[],
    nowDate:'',
    beginTime:'',
    endTime:'',
    isShowPop:false,
    currentDate: new Date().getTime(),
    minDate: new Date(2023, 0, 1).getTime(),
    currentTimeMin:'00:00',
    currentTimeMax:'23:59',
    nodeCount:1,
    nodeIndex:1,
    insIndex:0,
    nodeList:['节点1'],
    insList:['第1路电流设备','第2路电流设备'],
    nodeName:'节点1',
    insName:'第1路电流设备',
    isShowPopNode:false,
    isShowPopIns:false,
    nodeTempList:[],
    canvasImg:[],
    isShowPopMin:false,
    isShowPopMax:false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.deviceId = parseInt(options.id)
    this.data.deviceNum = options.num;
    this.data.nodeCount = parseInt(options.node_count)
    console.log('currentDate',this.data.currentDate)
    var ss = commonJs.formatTimeSimple(new Date());
    console.log('ss',ss)
    for(var index in this.data.nodeCount){
      this.data.nodeList.push('节点' + (index + 1))
    }

    var date = new Date();
    //年 getFullYear()：四位数字返回年份
    var year = date.getFullYear(); //getFullYear()代替getYear()
    //月 getMonth()：0 ~ 11
    var month = date.getMonth() + 1;
    //日 getDate()：(1 ~ 31)
    var day = date.getDate();
    //时 getHours()：(0 ~ 23)
    var hour = date.getHours();
    //分 getMinutes()： (0 ~ 59)
    var minute = date.getMinutes();
    //秒 getSeconds()：(0 ~ 59)
    var second = date.getSeconds();

    var minHour = 0;
    if(hour == 0){
      minHour = 0;
    }else{
      minHour = hour - 1;
    }
    var maxHour = hour;

    var hourBeginStr = minHour < 10 ? '0' + minHour : minHour;
    hourBeginStr += ':00';
    var hourEndStr = maxHour < 10 ? '0' + maxHour : maxHour;
    hourEndStr += ':59';

    this.data.currentTimeMin = hourBeginStr
    this.data.currentTimeMax = hourEndStr

    this.setData({
      currentTimeMin: hourBeginStr,
      currentTimeMax: hourEndStr,
    })

    console.log('nodeList',this.data.nodeList)
    this.data.nowDate = ss;
    this.setData({
      deviceNum:this.data.deviceNum,
      nowDate: ss,
      nodeList: this.data.nodeList
    })
    this.onHttpInit(ss);
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpInit: function (date) {
    var that = this
    that.setData({ isLoading: true})
    fetchApi.httpPost('/device/wenduList', {
      device_id:that.data.deviceId,
      date: that.data.nowDate,
      beginHour: that.data.currentTimeMin,
      endHour: that.data.currentTimeMax,
      nodeIndex: that.data.nodeIndex,
      insIndex: that.data.insIndex,
    }, function (res) {
      console.log("传感器设备列表数据", res)
      if (res.data.code == 0) {
        that.data.nodeTempList = res.data.data;
        that.setData({
          nodeTempList:  res.data.data
        })
        that.data.canvasImg = [];
        that.getMothElectro();
      }
      that.setData({  isLoading: false, loading: true, netWork: true,  })
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
    })
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  getMothElectro:function(){
    var windowWidth = 320;
    var that  = this
    try {
     var res = wx.getSystemInfoSync();
     windowWidth = res.windowWidth;
    } catch (e) {
     console.error('getSystemInfoSync failed!');
    }
    
    if(this.data.nodeTempList.length > 0){
      this.data.nowDate = this.data.nodeTempList[0].day;
      this.data.currentTimeMin = this.data.nodeTempList[0].beginHour;
      this.data.currentTimeMax = this.data.nodeTempList[0].endHour;
  
      that.setData({
        nowDate: this.data.nodeTempList[0].day,
        currentTimeMin: this.data.nodeTempList[0].beginHour,
        currentTimeMax: this.data.nodeTempList[0].endHour,
      })

      for(var index in this.data.nodeTempList){
        
        this.data.ecList.push({
          onInit: function (canvas, width, height, dpr) {
            const barChart = echarts.init(canvas, null, {
              width: width,
              height: height,
              devicePixelRatio: dpr // new
            });
            canvas.setChart(barChart);
            barChart.setOption(getTempOption());
            return barChart;
          }
        })
      }
    }
    
    for(var index in this.data.nodeTempList){
      var data_unit = this.data.nodeTempList[index].data_unit;
      var data_title = this.data.nodeTempList[index].data_unit;
      var categories = this.data.nodeTempList[index].times;
			var wenduData = this.data.nodeTempList[index].values;
			if(categories.length > 0){        
        let option = {
          grid: {
            containLabel: true,
            left:20
          },
          tooltip: {
            show: true,
            trigger: 'axis',
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: categories,
          },
          yAxis: {
            x: 'center',
            type: 'value',
            min: 0, //设置y轴最小值
            max: 100, //设置y轴最大值
            interval: 20, //设置y轴刻度间隔
            axisLabel: {
              // formatter: index == 0 ? `{value}`+data_unit : `{value}A` // 在每个x轴坐标都添加了单位
              formatter: `{value}`+data_unit // 在每个x轴坐标都添加了单位
            },
            splitLine: {
              lineStyle: {
                type: 'dashed'
              }
            }
          },
          series: [
            {
              name: data_title,//index == 0 ?'温度' : '电流',
              type: 'line',
              smooth: true,
              data: wenduData,//[18, 36, 65, 30, 78, 40, 33]
            },
          ]
        };
        
        this.data.ecList[index] =  {
          onInit: function (canvas, width, height, dpr) {
            const barChart = echarts.init(canvas, null, {
              width: width,
              height: height,
              devicePixelRatio: dpr // new
            });
            canvas.setChart(barChart);
            barChart.setOption(getTempOption(option));
            return barChart;
          }
        }

        // if(index == 0){
        //   that.setData({
        //     ecTemp: {
        //       onInit: function (canvas, width, height, dpr) {
        //         const barChart = echarts.init(canvas, null, {
        //           width: width,
        //           height: height,
        //           devicePixelRatio: dpr // new
        //         });
        //         canvas.setChart(barChart);
        //         barChart.setOption(getTempOption(option));
        //         return barChart;
        //       }
        //     }
        //   })
        // }else{
        //   that.setData({
        //     ecEle: {
        //       onInit: function (canvas, width, height, dpr) {
        //         const barChart = echarts.init(canvas, null, {
        //           width: width,
        //           height: height,
        //           devicePixelRatio: dpr // new
        //         });
        //         canvas.setChart(barChart);
        //         barChart.setOption(getTempOption(option));
        //         return barChart;
        //       }
        //     }
        //   })
        // }
			}
    }
    
    this.setData({
      ecList: this.data.ecList
    })
  },
  onClickDate(){
     this.setData({
       isShowPop : !this.data.isShowPop
     })
  },
  onClickDateMin(){
     this.setData({
       isShowPopMin : !this.data.isShowPopMin
     })
  },
  onClickDateMax(){
     this.setData({
      isShowPopMax : !this.data.isShowPopMax
     })
  },
  onCancle(){
     var that = this;
    this.setData({
      isShowPop : false,
      nodeTempList: that.data.nodeTempList
    })
  },
  onCancleHour(e){
     console.log('onCancleHour',e)
     var that = this;
     var type = e.currentTarget.dataset.htype;
     if(type == 'min'){
       this.onClickDateMin();
     }else{
       this.onClickDateMax()
     }
    //  this.setData({
    //   isShowPopHour : false,
    //   nodeTempList: that.data.nodeTempList
    //  })
  },
  onConfirm(event){
    var that = this;
    for(var index in this.data.nodeTempList){
     that.data.nodeTempList[index].canvasImg = '';
     that.data.nodeTempList[index].canvasWidth = 0
     that.data.nodeTempList[index].canvasHeight = 0
     that.setData({ nodeTempList:  that.data.nodeTempList});
    }
     console.log('onConfirm',event)
     const { detail, currentTarget } = event;
     const result = this.getResult(detail, currentTarget.dataset.type);
     console.log('result',result)
     console.log('detail',detail)
     var ss = commonJs.formatTimeSimple(new Date(detail));
     that.data.nowDate = ss;
     this.setData({
      nowDate:ss,
       currentDate: detail,
       isShowPop:false
     })
     this.onHttpInit();
  },
  onConfirmHour(e){
    console.log('onConfirmHour',e)
    
    var type = e.currentTarget.dataset.htype;
    var time = e.detail;
    if(type == 'min'){
      this.data.currentTimeMin = time;
      this.setData({
        currentTimeMin:time
      })
      this.onClickDateMin();
    }else{
      this.data.currentTimeMax = time;
      this.setData({
        currentTimeMax:time
      })
      this.onClickDateMax()
    }
    this.onHttpInit();

  },
  getResult(time, type) {
     const date = new Date(time);
     switch (type) {
       case 'datetime':
         return date.toLocaleString();
       case 'date':
         return date.toLocaleDateString();
       case 'year-month':
         return `${date.getFullYear()}/${date.getMonth() + 1}`;
       case 'time':
         return time;
       default:
         return '';
     }
  },
  formatData(type, value) {
     if (type === 'year') {
       return `${value}年`;
     }
     if (type === 'month') {
       return `${value}月`;
     }
     return value;
  },
  touchHandler: function (e) { //当月用电触摸显示
    yuelineChart.showToolTip(e, { //showToolTip图表中展示数据详细内容
     background: '#7cb5ec',
     format: function (item, category) {
      return category + '日 ' + item.name + ':' + item.data
     }
    });
  },
})